package com.gy.assistant.ui;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.google.android.material.badge.BadgeDrawable;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import org.json.JSONException;
import org.json.JSONObject;

import im.zego.zim.ZIM;
import im.zego.zim.entity.ZIMMessageDeleteConfig;
import im.zego.zim.enums.ZIMConnectionEvent;
import im.zego.zim.enums.ZIMConnectionState;
import im.zego.zim.enums.ZIMConversationType;
import com.gy.assistant.ui.chat.group.ZIMGroupSearchFilterActivity;

import com.gy.assistant.ui.conversationlist.ConversationListActivity;

import com.gy.assistant.ui.friend.ZIMAddFriendActivity;
import com.gy.assistant.ui.friend.search.ui.ZIMFriendSearchFilterActivity;

import com.gy.assistant.ui.meeting.MeetingInviteActivity;
import com.gy.assistant.LoginActivity;
import com.gy.assistant.R;
import com.gy.assistant.SDKManager;
import com.gy.assistant.push.MyZIMPushReceiver;
import com.gy.assistant.ui.chat.group.ZIMGroupChatActivity;
import com.gy.assistant.ui.chat.group.ZIMGroupChatCreateActivity;
import com.gy.assistant.ui.chat.group.ZIMGroupChatJoinActivity;
import com.gy.assistant.ui.chat.peer.ZIMPeerChatActivity;
import com.gy.assistant.ui.chat.peer.ZIMPeerChatCreateActivity;
import com.gy.assistant.ui.chat.room.ZIMRoomCreateActivity;
import com.gy.assistant.ui.chat.room.ZIMRoomJoinActivity;
import com.gy.assistant.ui.search.SearchFilterActivity;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    public BottomNavigationView bottomNavigationView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bindView();

        setEventHandler();
        requestPermissions();

        MyZIMPushReceiver.event = new MyZIMPushReceiver.Event() {
            @Override
            public void onRegistered(String regID) {
                Log.i("", "push register id: " + regID);
            }

            @Override
            public void onNotificationClicked(String message) {
                try {
                    JSONObject jsonObject = new JSONObject(message);
                    String conversationID = jsonObject.getString("conversation_id");
                    String conversationName = jsonObject.getString("conversation_name");
                    int conversationType = jsonObject.getInt("conversation_type");
                    ZIMConversationType type = ZIMConversationType.getZIMConversationType(conversationType);

                    if (type == ZIMConversationType.GROUP) {
                        ZIMGroupChatActivity.actionStart(MainActivity.this, conversationID, conversationName,"");
                    } else if (type == ZIMConversationType.PEER) {
                        ZIMPeerChatActivity.actionStart(MainActivity.this, conversationID, conversationName,"");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };
    }

    public void requestPermissions() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 如果没有，获取读取和写入动态权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 100);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.top_nav, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.navigation_create_peer_chat:
                ZIMPeerChatCreateActivity.actionStart(this);
                break;
            case R.id.navigation_create_group_chat:
                ZIMGroupChatCreateActivity.actionStart(this);
                break;
            case R.id.navigation_join_group_chat:
                ZIMGroupChatJoinActivity.actionStart(this);
                break;
            case R.id.navigation_create_room_chat:
                ZIMRoomCreateActivity.actionStart(this);
                break;
            case R.id.navigation_join_room_chat:
                ZIMRoomJoinActivity.actionStart(this);
                break;
            case R.id.navigation_all_pinned_list:
                ConversationListActivity.actionStart(this,true);
                break;
            case R.id.navigation_create_meeting:
                MeetingInviteActivity.actionStart(this,null);
                break;
			case R.id.navigation_message_search:
            	SearchFilterActivity.actionStart(this, null,null, 0);
            	break;
        	case R.id.navigation_group_search:
            	ZIMGroupSearchFilterActivity.actionStart(this, null, null);
                break;
            case R.id.navigation_add_friend:
                ZIMAddFriendActivity.actionStart(this);
				break;
	        case R.id.navigation_friend_search:
	            ZIMFriendSearchFilterActivity.actionStart(this);
	            break;
        	case R.id.clear_all_conversation_message:
            	SDKManager.sharedInstance().getZim().deleteAllConversationMessages(new ZIMMessageDeleteConfig(),null);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onStart() {
        super.onStart();
        SDKManager.sharedInstance().showDebugLog(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        SDKManager.sharedInstance().hideDebugLog(this);
    }

    @Override
    public void finish() {

        clearLoginInfo();
        SDKManager.sharedInstance().logout();

        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);

        super.finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void bindView() {
        bottomNavigationView = findViewById(R.id.bottom_nav_view);
        AppBarConfiguration appBarConfiguration =
            new AppBarConfiguration
                .Builder(R.id.navigation_message, R.id.navigation_address_book,
                         R.id.navigation_group_list, R.id.navigation_user_info)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main);
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(bottomNavigationView, navController);
    }

    private void setEventHandler() {
        SDKManager.sharedInstance().setConversationTotalUnreadMessageCountUpdatedCallback(new SDKManager.OnConversationTotalUnreadMessageCountUpdatedCallback() {
            @Override
            public void onConversationTotalUnreadMessageCountUpdated(ZIM zim, int totalUnreadMessageCount) {
                BadgeDrawable badgeDrawable = bottomNavigationView.getOrCreateBadge(R.id.navigation_message);
                if (totalUnreadMessageCount > 0) {
                    badgeDrawable.setVisible(true);
                    badgeDrawable.setNumber(totalUnreadMessageCount);
                } else {
                    badgeDrawable.setVisible(false);
                    badgeDrawable.clearNumber();
                }
            }
        });

        SDKManager.sharedInstance().setLoginStateCallback(new SDKManager.OnLoginStateCallback() {
            @Override
            public void onConnectionStateChanged(ZIM zim, ZIMConnectionState state, ZIMConnectionEvent event, JSONObject extendedData) {
                if (event == ZIMConnectionEvent.KICKED_OUT) {
                    clearLoginInfo();
                    Toast.makeText(MainActivity.this, "User kicked out", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
            }
        });
    }

    private void clearLoginInfo() {
        SharedPreferences sp = getSharedPreferences(LoginActivity.SP_FILE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(LoginActivity.SP_FILE_ID_KEY, null);
        editor.putString(LoginActivity.SP_FILE_NAME_KEY, null);
        editor.putInt(LoginActivity.SP_FILE_LAST_PUSH_MODE, 0);
        editor.apply();
    }
}
